In JavaScript, call()
, apply()
, and bind()
are methods used to control the value of this
when calling a function. Although they are similar, there are key differences in how they are used.
call()
func.call(thisArg, arg1, arg2, ...)
Example:
apply()
func.apply(thisArg, [argsArray])
Example:
bind()
this
value and optional preset arguments. Unlike call
and apply
, it does not invoke the function immediately.const boundFunc = func.bind(thisArg, arg1, arg2, ...)
this
value for later use.Example:
Feature | call() | apply() | bind() |
---|---|---|---|
Invocation | Immediate | Immediate | Returns a new function (delayed) |
Arguments | Passed individually | Passed as an array | Passed individually or preset |
Use Case | Known argument count | Unknown argument count or array | Function reuse with fixed context |
Here are more detailed examples of call()
, apply()
, and bind()
in different scenarios to help you understand their practical uses:
call()
for Method BorrowingYou can borrow methods from other objects using call()
.
apply()
for Math Operationsapply()
is useful when you need to pass an array of arguments, such as with Math
functions.
bind()
for Function Bindingbind()
is helpful when you need a function with a fixed this
context to be called later.
call()
, apply()
, and bind()
in Constructor FunctionsYou can use them to inherit properties from other constructors.
bind()
with Partially Applied FunctionsYou can create a function with preset arguments using bind()
.
apply()
with Variable ArgumentsWhen you donβt know how many arguments will be passed, use apply()
.
bind()
with Event ListenersEnsure the correct this
context with bind()
in event handlers.
Feature | call() | apply() | bind() |
---|---|---|---|
Invocation | Immediate | Immediate | Returns a new function (delayed) |
Arguments | Passed individually | Passed as an array | Passed individually or preset |
this Binding | Binds temporarily during call | Binds temporarily during call | Binds permanently for reuse |
Common Use | Method borrowing, chaining | Variable argument functions | Event listeners, callbacks |